package dao;

import bean.Goods;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.MyDataSource;

import java.sql.SQLException;
import java.util.List;

public class GoodsDao {
    //这里是对数据库中goods表进行增删改查
    public static boolean addGoods(Goods goods) throws SQLException {
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="insert into goods(id,name,price,count) value(?,?,?,?)";
        int num=runner.update(sql,new Object[] {goods.getId(),goods.getName(),goods.getPrice(),goods.getCount()});
        if(num>0)
            return true;
        else
            return false;
    }

    public static boolean delGoods(){
        return true;
    }

    public  static boolean editGoods(){
        return true;
    }

    public static Goods findById(String id) throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="select * from goods where id=?";
        Goods goods=(Goods) runner.query(sql,new BeanHandler(Goods.class),new Object[] {id});
        return goods;
    }

    public static List<Goods> findByName(String name) throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="select * from goods where name like ?";
        List<Goods> goodsList=(List) runner.query(sql,new BeanListHandler(Goods.class),new Object[] {name+"%"});
        return goodsList;
    }

    public static List<Goods> findAll() throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="select * from goods";
        List<Goods> goodsList=(List) runner.query(sql,new BeanListHandler(Goods.class));
        return goodsList;
    }

}
